package com.projles.util;

import java.util.HashMap;

import android.content.Context;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Vibrator;

import com.projles.OpcoesActivity;
import com.projles.R;
 

public class Player{

	private Context context;

	public static final int CLICK = 1;
	public static final int ACERTO = 2;
	public static final int ERRO = 3;
	public static final int APLAUSOS = 4;
	
	
	private float volume;
	private boolean vibra;
	
	private SoundPool soundPool;
	private HashMap<Integer, Integer> soundPoolMap;
	
	private Vibrator vibrator;
	private SharedPreferences config;
	
	private static Player player;
	
	public static Player getPlayer(Context context) {
		if (player == null) {
			player = new Player(context);
		}
		player.setContext(context);
		return player;
	}

	private Player(Context context) {
		config = context.getSharedPreferences(OpcoesActivity.PREFS_NAME, 0);
		vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
		setContext(context);
		initSounds();
		volume = getVolume();
		setMute(config.getBoolean("mute", false));
		setVibra(config.getBoolean("vibra", true));
		
	}
	
	private void setContext(Context context) {
		this.context = context;
	}
	
	private Context getContext() {
		return this.context;
	}
	
	public void setMute(boolean mute) {
		if (mute) {
			volume = 0;
		} else {
		    volume = getVolume();
		}
	}
	
	public boolean isMuted() {
		return volume == 0;
	}
	
	public void setVibra(boolean vibra) {
		this.vibra = vibra;
	}
	
	public boolean isVibra() {
		return vibra;
	}
	
	private float getVolume() {
		AudioManager mgr = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
	    float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
	    float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);    
	    return streamVolumeCurrent / streamVolumeMax;
	}

	private void initSounds() {
	     soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
	     soundPoolMap = new HashMap<Integer, Integer>();
	     soundPoolMap.put(ERRO, soundPool.load(getContext(), R.raw.erro1, 1));
	     soundPoolMap.put(ACERTO, soundPool.load(getContext(), R.raw.acerto, 1));
	     soundPoolMap.put(CLICK, soundPool.load(getContext(), R.raw.clique, 1));
	     soundPoolMap.put(APLAUSOS, soundPool.load(getContext(), R.raw.aplausos, 1));
	}
	
	public void playSound(int sound, int tempo_vibra) {
		vibra(tempo_vibra);
	    soundPool.play(soundPoolMap.get(sound), volume, volume, 1, 0, 1f);     
	}
	
	public void playSound(int sound) {
		playSound(sound, 0);    
	}
	
	public void vibra(int tempo) {
		if (vibra) {
			vibrator.vibrate(tempo);
		}
	}

	public void erro() {
	    playSound(ERRO, 300);
	}
	
	public void acerto() {
	    playSound(ACERTO, 300);
	}
	
	public void aplausos() {
	    playSound(APLAUSOS, 300);
	}
	
	
	public void click() {
	    playSound(CLICK);
	} 

}
